<template>
    <BasicModal
      v-bind="$attrs"
      @register="registerModal"
      show-footer
      width="40%"
      @ok="handleSubmit"
    >
      <template #title>
        {{ isUpdate ? '编辑' : '新增' }}
      </template>
      <template #footer>
        <a-button @click="closeModal" :loading="btnLoading">取消</a-button>
        <a-button
          type="primary"
          @click="handleSubmit(false)"
          :loading="btnLoading"
          >保存</a-button
        >
      </template>
      <BasicForm @register="registerForm">
      </BasicForm>  
    </BasicModal>
  </template>
  <script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useThrottleFn } from '@vueuse/core';
  import { defHttp } from '@/utils/http/axios';
  import { listToTree } from '@/utils/helper/treeHelper';
  const emit = defineEmits(['success', 'register']);
  let isUpdate = ref(true);
  const btnLoading = ref(true);
  const { createMessage } = useMessage();
  const [
    registerForm,
    { resetFields, getFieldsValue, setFieldsValue, validate },
  ] = useForm({
    labelWidth: 100,
    schemas: [
   
      {
        field: 'id',
        component: 'Input',
        label: 'id',
        show: false,
      },
      {
        field: 'name',
        component: 'Input',
        label: '姓名',
        required: true,
      },
      {
        field: 'username',
        component: 'Input',
        label: '用户名',
        required: true,
      },
      {
        field: 'password',
        component: 'Input',
        label: '密码',
        componentProps: {
          type: 'password',
        },
      },
      {
        field: 'repassword',
        component: 'Input',
        label: '确认密码',
        dynamicRules: ({ values }) => {
          return isUpdate.value? [] : [
            {
              required: true,
              validator: (_, value) => {
                if (!value) {
                  return Promise.reject('密码不能为空');
                }
                if (value !== values.repassword) {
                  return Promise.reject('两次输入的密码不一致!');
                }
                return Promise.resolve();
              },
            },
          ];
        },
        componentProps: {
          type: 'password',
        }
      },
      {
        field:'sex',
        component: 'RadioGroup',
        label: '性别',
        componentProps: {
          options: [
            { label: '男', value: '1' },
            { label: '女', value: '0' },
          ],
        },
      },
      {
        field: 'phone',
        component: 'Input',
        label: '手机',
      },
      {
        field: 'email',
        component: 'Input',
        label: '邮箱',
      },
      {
        field: 'roleId',
        component: 'ApiSelect',
        label: '角色',
        componentProps: {
          api: '/admin/main/roleList',
          valueField: 'id',
          labelField: 'name',
        },
      },
      {
        field: 'memo',
        component: 'InputTextArea',
        label: '备注',
      },
    ],
    showActionButtonGroup: false,
    baseColProps: { span: 24 },
  });
 
  function getUserRoles(adminId: number) {
    defHttp.get({ url: `/admin/main/roleListByAdmin/${adminId}` }).then((res) => {
      setFieldsValue({ roleId: res });
    });
  }
  const [registerModal, { closeModal, changeLoading }] =
  useModalInner(async (data) => {
      resetFields();
      debugger
      changeLoading(true);
      btnLoading.value = true;
      isUpdate.value =!!data?.isUpdate;
      if (isUpdate.value) {
        setFieldsValue({ ...data.record, password: ''});
        getUserRoles(data.record.id);
      } 
      changeLoading(false);
      btnLoading.value = false;
    });
  const handleSubmit = useThrottleFn(doSubmit, 1000);
  async function doSubmit(hasNext: boolean) {
    try {
      changeLoading(true);
      btnLoading.value = true;
      const values = await validate();
      if (isUpdate.value) {
        const res = await defHttp.post({ url: '/admin/admin/update', data: values });
        createMessage.success(res);
      } else {
        const res = await defHttp.post({ url: '/admin/admin/save', data: values });
        createMessage.success(res);
      }
      emit('success');
      closeModal();
    } finally {
      btnLoading.value = false;
      changeLoading(false);
    }
  }
  </script>
  